<template>
  <div class="page-calendar" style="height: 100%">
    <div class="calendar-head" style="margin-top:10px;margin-left:10px">
      <div class="calendar-titbox">

        <el-row style="width:100%">
          <span style="float:left">
            <h1 style="float: left">{{rangeText}}</h1>
            <div style="float: left;margin-left: 15px;">
              <el-button size="mini" type="primary" plain @click="setView('day')" :type="calendarView == 'day' ? 'primary' : 'default'">{{$L('日')}}</el-button>
              <el-button size="mini" type="primary" plain @click="setView('week')" :type="calendarView == 'week' ? 'primary' : 'default'">{{$L('周')}}</el-button>
              <el-button size="mini" type="primary" plain @click="setView('month')" :type="calendarView == 'month' ? 'primary' : 'default'">{{$L('月')}}</el-button>

            </div>
            <div style="float: left;margin-left: 15px;">任务状态：<el-select v-model="taskQuery.flowItemNameList" collapse-tags multiple placeholder="请选择任务状态" @change="taskQueryChange">
              <el-option
                v-for="item in taskFlowItems"
                :key="item.status"
                :label="item.title"
                :value="item.status">
              </el-option>
            </el-select></div>
            <div v-if="leaderStaffs.length>0" style="float: left;margin-left: 15px;">负责人：<el-select v-model="taskQuery.curStaffCode"  placeholder="请选择任务责任人" @change="taskQueryChange">
              <el-option
                v-for="item in leaderStaffs"
                :key="item.staffCode"
                :label="item.name"
                :value="item.staffCode">
              </el-option>
            </el-select></div>

          </span>
          <span style=" float:right;text-align: right;padding-right: 20px;line-height: 36px">
            <el-button size="mini" type="primary" plain @click="refreshQuery" icon="el-icon-refresh">重置</el-button>
            <el-button size="mini" type="primary" plain @click="preMonth" icon="el-icon-caret-left"></el-button>
            <el-button size="mini" type="primary" plain @click="afterMonth" icon="el-icon-caret-right"></el-button>
            <el-button size="mini" type="primary" plain @click="curMonth">{{$L('今天')}}</el-button>
          </span>
        </el-row>
      </div>
    </div>
    <div class="calendar-box" style="padding:0 10px 6px">
      <Calendar
        ref="cal"
        :view="calendarView"
        :week="calendarWeek"
        :month="calendarMonth"
        :theme="calendarTheme"
        :template="getTemplate"
        :schedules="list"
        :taskView="true"
        :useCreationPopup="true"
        @beforeCreateSchedule="onBeforeCreateSchedule"
        @beforeClickSchedule="onBeforeClickSchedule"
        @beforeUpdateSchedule="onBeforeUpdateSchedule"
        disable-click/>
    </div>
    <div class="calendar-menu" :style="calendarMenuStyles">
      <TaskMenu ref="calendarTaskMenu" :task="calendarTask" updateBefore/>
    </div>
    <TaskAdd v-if="taskAddRef.ready" :curStaffCode="taskQuery.curStaffCode" ref="taskAddRef" :add_url="web_manager.add_url" :ws_url="web_manager.ws_url" :taskId="task_id" :start_at="start_at" :end_at="end_at"></TaskAdd>



  </div>
</template>

<script>

import {$A} from './functions/common.js'
// import Vue from "vue";

import 'tui-calendar-hi/dist/tui-calendar-hi.css'

import ViewUI from 'view-design-hi';

import Calendar from "./components/Calendar";
import moment from "moment";
import TaskMenu from "./components/TaskMenu";
import TaskAdd from "./calendarItem/TaskAdd";
// import axios from "axios";
// axios.defaults.baseURL =`https://unicoder.zippro.cn/`

import {
// Row,
// Col,
// Button,
// Divider,
// Avatar,
// Tooltip,
// Popover,
// Dropdown,
// DropdownMenu,
// DropdownItem,
// Dialog,
//   Select,
//   Option,
MessageBox,
  Message
} from 'element-ui';


// Vue.component('ElSelect', Select);
// Vue.component('ElOption', Option);
// Vue.component('ElRow', Row);
// Vue.component('ElCol', Col);
// Vue.component('ElButton', Button);
// Vue.component('ElDivider', Divider);
// Vue.component('EAvatar', Avatar);
// Vue.component('ETooltip', Tooltip);
// Vue.component('EPopover', Popover);
// Vue.component('ElDropdown', Dropdown);
// Vue.component('ElDropdownMenu', DropdownMenu);
// Vue.component('ElDropdownItem', DropdownItem);
// Vue.component('ElDialog', Dialog);
Vue.component('MessageBox', MessageBox );
Vue.component('Message', Message );

Vue.prototype.$message = Message;

Vue.use(ViewUI, {
  modal: {
    checkEscClose: true
  }
});

export default {
  components: {TaskMenu, Calendar,TaskAdd},
  provide() {
    const provider = {};
    const self = this;
    Object.defineProperty(provider, 'root', {
      enumerable: true,
      get: () => self
    });
    return provider;
  },
  props:{
    datamanager: {
      type: String, default: ` `
    },
  },
  data() {
    return {
      wsurl:"",
      taskQuery:{
        flowItemNameList:["start","progress","followed","test"],  //任务状态
      },
      flowItemNameTemp:["start","progress","followed","test"],  //任务状态
      isLocal:false,  //是否本地环境
      leaderStaffs:[],  //领导
      curStaffCode:"",  //当前账号
      taskFlowItems:  [
        {title:"待处理","name": "待处理","status": "start"},
        {title:"进行中","name": "进行中","status": "progress"},
        {title:"待跟进","name": "待跟进","status": "followed"},
        {title:"待测试","name": "待测试","status": "test"},
        {title:"已完成","name": "已完成","status": "end"},
        {title:"已取消","name": "已取消","status": "cancel"},
      ],
      web_manager:{
        get_api:"",
        del_api:"",
        upd_api:"",
        add_url:'',
        staff_api:''
      },  //前端页面属性配置

      loginUserInfo: "", //当前登录用户
      start_at:"",
      end_at:"",
      taskAddRef:{
        ready:false,
      },
      taskMenu:{
        ready:false,
      },
      websocket:null,

      task_id:0,
      taskDetail:{},
      cacheTasks:[],
      taskCompleteTemps:[],
      ready:false,
      lists: [],
      nowTime:$A.Time(),

      rangeText: 'Calendar',
      rangeTime: [],

      calendarView: 'month',
      calendarWeek: {
        dayNames: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
        taskView:false,
        eventView:false,
      },
      calendarMonth: {},
      calendarTheme: {},
      calendarTemplate: {},
      calendarTask: {},
      calendarMenuStyles: {
        top: 0,
        left: 0
      },
      loadTimeout: null,
    }
  },

  activated() {
    this.$refs.cal.resetRender();
    this.setRenderRange();
  },
  mounted() {
    console.log(this.datamanager)
    this.web_manager = JSON.parse(this.datamanager)
    this.web_manager.add_url = this.setUrlParam(this.web_manager.add_href,this.web_manager.add_param)
    this.web_manager.get_api = this.setUrlParam(this.web_manager.get_href,this.web_manager.get_param)
    this.web_manager.upd_api = this.setUrlParam(this.web_manager.upd_href,this.web_manager.upd_param)
    this.web_manager.del_api = this.setUrlParam(this.web_manager.del_href,this.web_manager.del_param)
    this.web_manager.staff_api = this.setUrlParam(this.web_manager.staff_href,this.web_manager.staff_param)
    // console.log(this.web_manager)

    if(localStorage.getItem("taskQuery")){
      this.taskQuery = JSON.parse(localStorage.getItem("taskQuery"));
    }
    if(localStorage.getItem("loginUserInfo")){
      this.loginUserInfo = JSON.parse(localStorage.getItem("loginUserInfo"));
      this.taskQuery.curStaffCode = this.loginUserInfo.staffCode
    }


    this.setRenderRange();
    setTimeout(()=>{
      this.setRenderRange();
    },100)
  },

  deactivated() {
    this.$store.dispatch("forgetTaskCompleteTemp", true);
  },

  computed: {
    list() {
      this.taskCompleteTemps = this.cacheTasks
      const filterTask = (task, chackCompleted = true) => {
        if (task.archived_at) {
          return false;
        }
        if (task.complete_at && chackCompleted === true) {
          return false;
        }
        if (!task.end_at) {
          return false;
        }
        return task.owner;
      }
      if(!this.cacheTasks){
        return
      }
      let array = this.cacheTasks.filter(task => filterTask(task));
      if (this.taskCompleteTemps.length > 0) {
        let tmps = this.cacheTasks.filter(task => this.taskCompleteTemps.includes(task.id) && filterTask(task, false));
        if (tmps.length > 0) {
          array = $A.cloneJSON(array)
          array.push(...tmps);
        }
      }
      return $A.transforTasks(array).map(data => {
        const isAllday = $A.rightExists(data.start_at, "00:00:00") && $A.rightExists(data.end_at, "23:59:59")

        const task = {
          id: data.id,
          isEdit:data.isEdit,
          calendarId: String(data.project_id),
          title: data.name,
          owner_name:data.owner_name,
          sub_owner_name:data.sub_owner_name,
          body: data.desc,
          isAllDay: isAllday,
          category: isAllday ? 'allday' : 'time',
          start: $A.Date(data.start_at).toISOString(),
          end: $A.Date(data.end_at).toISOString(),
          color: "#515a6e",
          bgColor: data.color || '#E3EAFD',
          borderColor: data.p_color,
          priority: '',
          preventClick: true,
          preventCheckHide: true,
          isChecked: !!data.complete_at,
          //
          complete_at: data.complete_at,
          start_at: data.start_at,
          end_at: data.end_at,
          _time: data._time
        };
        if (data.p_name) {
          let priorityStyle = `background-color:${data.p_color}`;
          task.priority = `<span class="priority" style="${priorityStyle}">${data.p_name}</span>`;
        }
        if (data.sub_my && data.sub_my.length > 0) {
          task.title = `[+${data.sub_my.length}] ${task.title}`
        }
        if (data.sub_top === true) {
          task.title = `[${this.$L('子任务')}] ${task.title}`
        }
        if (data.flow_item_name) {
          task.title = `[${data.flow_item_name}] ${task.title}`
        }
        if(!data.isEdit){
          task.title = `[🔒] ${task.title}`
        }
        if (data.complete_at) {
          task.color = "#c3c2c2"
          task.bgColor = "#f3f3f3"
          task.borderColor = "#e3e3e3"
        } else if (data.overdue || $A.Date(data.end_at, true) < this.nowTime) {
          task.title = `[${this.$L('超期')}] ${task.title}`
          task.color = "#515a6e"
          task.bgColor = 'rgba(243,8,67,0.24)'
          task.priority+= `<span class="overdue">${this.$L('超期未完成')}</span>`;
        }

        if (data.flow_item_name=== '已完成')  {
          task.bgColor = "#f3f3f3"
        }
        if (!task.borderColor) {
          task.borderColor = task.bgColor;
        }
        return task;
      });
    },
    getTemplate(){
      this.calendarTemplate = {
        popupDetailBody: (schedule)=> {
          let curTaskInfo = this.cacheTasks.find(item=>item.id=== schedule.id)
          let sub_owner_name=curTaskInfo.sub_owner_name==='undefined'?'':curTaskInfo.sub_owner_name
          return `
                <div>
                <p>主负责人：${curTaskInfo.owner_name}</p>
                <p>次负责人：${sub_owner_name}</p>
                <p>=================================</p>
                    <p>${schedule.body}</p>

                </div>`;
        },
        popupEdit: function() {
          return '编辑';
        },
        popupDelete: function() {
          return '删除';
        }
      }
      return this.calendarTemplate
    },
  },

  methods: {
    refreshQuery(){
      this.taskQuery.flowItemNameList = this.flowItemNameTemp
      this.taskQuery.curStaffCode = this.loginUserInfo.staffCode
      this.setRenderRange()
    },
    departmentStaff(){
      if(this.isLocal){
        axios({
          method: 'post',
          // url: this.web_manager.del_api,
          url: this.web_manager.staff_api,
          data: {
            "staff_code": this.loginUserInfo.staffCode,
          }
        }).then((res) => {
          if (res.data.code !== 0) {
            this.$message({
              message: res.data.desc,
              type: 'error',
              duration: 1000,
              showClose: true
            })
          }else{
            console.log(res.data.data)
            this.leaderStaffs = res.data.data
          }
        })
      }else{
        this.$magicaltool.request.axios({
          $vue:this,method:"post",contentType:"application/json",
          url:this.web_manager.staff_api,
          responseType:"",
          data:{
            "staff_code": this.loginUserInfo.staffCode,
          }
        }).then((res)=> {
          if (res.code !== 0) {
            this.$message({
              message: res.desc,
              type: 'error',
              duration: 1000,
              showClose: true
            })
          }else{
            this.leaderStaffs = res.data
          }
        })
      }
    },
    taskQueryChange(){
      localStorage.setItem("taskQuery", JSON.stringify(this.taskQuery))
      this.setRenderRange()
    },
    /**
     * websocket
     * @returns {*}
     * @param url
     */
    ws(url){
      let socket;
      let newurl = url
      if(url){
        this.wsurl = url
      }else{
        newurl = this.wsurl
      }


      socket = this.connect(socket, newurl);
      return socket;
    },
    connect(socket,newurl) {
  socket = new WebSocket(newurl);

  socket.onopen = (event) => {
    console.log('Connection established');
  };

  socket.onmessage = (event) => {
    console.log('Client received a message', event);
    let data = JSON.parse(event.data);
    let fun = data.fun;
    let param = data.param;
    if (fun === 'closeDialog') {
      this.closeDialog(param);
    }
  };

  socket.onclose = (event) => {
    console.log('Client lost connection, attempting to reconnect...');
    setTimeout(() => {
      this.ws(); // 重新调用 connect 方法以实现重连
    }, 1000);
  };

  socket.onerror = (event) => {
    console.log('Client error', event);
    socket.close(); // 关闭并触发 onclose，进行重连
  };
  return socket
},

    setUrlParam(url,paramList) {
      let urlParam = ''
      // return url
      paramList.forEach(item => {
        if (item.value.toString().startsWith('MC.vdata.')) {
          item.value = this.MC.vdata[item.value.split('MC.vdata.')[1]]
        }
        else if (item.value.toString().startsWith('MC.url_param(')) {
          item.value = this.MC.url_param(item.value.split("MC.url_param('")[1].replace("')",""))
        }
        urlParam += `${item.name}${item.type}${item.value}&`
      })
      urlParam = urlParam.substring(0, urlParam.length - 1)
      if(url.indexOf('?')>-1){
        url = url+'&'+urlParam
      }else {
        url = url+'?'+urlParam
      }
      return url

    },
    $L(text){
      return text
    },
    getTask(time) {
      const timeStart = $A.Date($A.formatDate(time[0] + " 00:00:00")),
      timeEnd = $A.Date($A.formatDate(time[1] + " 23:59:59"));
      let startTime = timeStart.toLocaleString('chinese',{hour12:false})
      let endTime = timeEnd.toLocaleString('chinese',{hour12:false})
      startTime = startTime.replace(/\//g, '-');
      endTime = endTime.replace(/\//g, '-');
      let flowItemNameList = []
      this.taskFlowItems.forEach(item=>{
        if(this.taskQuery.flowItemNameList.indexOf(item.status)!==-1){
          flowItemNameList.push(item.name)
        }
      })
      if(this.isLocal){
        axios({
          method: 'post',
          url: this.web_manager.get_api,
          data: {
            "start_time": startTime,
            "end_time": endTime,
            "staff_code":this.taskQuery.curStaffCode,
            "login_staffCode":this.loginUserInfo.staffCode,
            'flow_item_name_list':flowItemNameList,
          }
        }).then((res) => {
          if (res.data.code !== 0) {
            this.$message({
              message: res.data.desc,
              type: 'error',
              duration: 1000,
              showClose: true
            })
          }
          else{
            let cacheTasks = res.data.data
            this.cacheTasks = cacheTasks.map(item=>{
              return {
                "id": item.id,
                "isPrivate":false,
                "isReadOnly":true,
                isEdit:item.isEdit,
                "owner_name":item.owner_name,
                "sub_owner_name":item.sub_owner_name,
                "parent_id": item.parent_id,
                "project_id": item.project_id,
                "column_id": item.column_id,
                "dialog_id": item.dialog_id,
                "flow_item_id": item.flow_item_id,
                "flow_item_name": item.flow_item_name,
                "name": item.name,
                "color": item.color,
                "desc": item.task_desc,
                "start_at": item.start_at,
                "end_at": item.end_at,
                "archived_at": item.archived_at,
                "archived_userid": item.archived_userid,
                "archived_follow": item.archived_follow,
                "complete_at": item.complete_at,
                "userid": item.userid,
                "visibility": item.visibility,
                "p_level": item.p_level,
                "p_name": item.p_name,
                "p_color": item.p_color,
                "sort": item.sort,
                "loop": item.loop,
                "loop_at": item.loop_at,
                "created_at": item.created_at,
                "updated_at": item.updated_at,
                "deleted_at": item.deleted_at,
                "deleted_userid": item.deleted_userid,
                "owner": item.owner,
                "file_num": item.file_num,
                "msg_num": item.msg_num,
                "sub_num": item.sub_num,
                "sub_complete":item.sub_complete,
                "percent": item.percent,
                "today": item.today,
                "overdue": item.overdue,
                "task_user": [
                  {
                    "id": 30399,
                    "project_id": 12307,
                    "task_id": 26361,
                    "task_pid": 26361,
                    "userid": 1,
                    "owner": 1,
                    "created_at": "2024-08-16 09:00:02",
                    "updated_at": "2024-08-16 09:00:02"
                  }
                ],
                "task_tag": item.task_tag,
                "project_name": item.project_name,
                "column_name": item.column_name,
                "visibility_appointor": item.visibility_appointor,
              }
            })
          }
        })
      }else{
        this.$magicaltool.request.axios({
          $vue:this,method:"post",contentType:"application/json",
          url:this.web_manager.get_api,
          responseType:"",
          data:{
            "start_time": startTime,
            "end_time": endTime,
            "staff_code":this.taskQuery.curStaffCode,
            "login_staffCode":this.loginUserInfo.staffCode,
            'flow_item_name_list':flowItemNameList,
          }
        }).then((res)=> {
          if (res.code !== 0) {
            this.$message({
              message: res.desc,
              type: 'error',
              duration: 1000,
              showClose: true
            })
          }else{
            let cacheTasks = res.data
            this.cacheTasks = cacheTasks.map(item=>{
              return {
                "id": item.id,
                "isPrivate":false,
                "isReadOnly":true,
                isEdit:item.isEdit,
                "owner_name":item.owner_name,
                "sub_owner_name":item.sub_owner_name,
                "parent_id": item.parent_id,
                "project_id": item.project_id,
                "column_id": item.column_id,
                "dialog_id": item.dialog_id,
                "flow_item_id": item.flow_item_id,
                "flow_item_name": item.flow_item_name,
                "name": item.name,
                "color": item.color,
                "desc": item.task_desc,
                "start_at": item.start_at,
                "end_at": item.end_at,
                "archived_at": item.archived_at,
                "archived_userid": item.archived_userid,
                "archived_follow": item.archived_follow,
                "complete_at": item.complete_at,
                "userid": item.userid,
                "visibility": item.visibility,
                "p_level": item.p_level,
                "p_name": item.p_name,
                "p_color": item.p_color,
                "sort": item.sort,
                "loop": item.loop,
                "loop_at": item.loop_at,
                "created_at": item.created_at,
                "updated_at": item.updated_at,
                "deleted_at": item.deleted_at,
                "deleted_userid": item.deleted_userid,
                "owner": item.owner,
                "file_num": item.file_num,
                "msg_num": item.msg_num,
                "sub_num": item.sub_num,
                "sub_complete":item.sub_complete,
                "percent": item.percent,
                "today": item.today,
                "overdue": item.overdue,
                "task_user": [
                  {
                    "id": 30399,
                    "project_id": 12307,
                    "task_id": 26361,
                    "task_pid": 26361,
                    "userid": 1,
                    "owner": 1,
                    "created_at": "2024-08-16 09:00:02",
                    "updated_at": "2024-08-16 09:00:02"
                  }
                ],
                "task_tag": item.task_tag,
                "project_name": item.project_name,
                "column_name": item.column_name,
                "visibility_appointor": item.visibility_appointor,
              }
            })
          }
        })
      }


    },

    preMonth() {
      this.$refs.cal.getInstance().prev();
      this.setRenderRange()
    },

    curMonth() {
      this.$refs.cal.getInstance().today();
      this.setRenderRange()
    },

    afterMonth() {
      this.$refs.cal.getInstance().next();
      this.setRenderRange()
    },

    setView(view) {
      this.calendarView = view;
      this.setRenderRange()
    },

    setRenderRange() {
      this.departmentStaff()
      this.$nextTick(() => {
        const cal = this.$refs.cal.getInstance();
        let options = cal.getOptions();
        let viewName = cal.getViewName();
        let html = [];
        if (viewName === 'day') {
          html.push(this.currentCalendarDate('YYYY.MM.DD'));
        } else if (viewName === 'month' &&
          (!options.month.visibleWeeksCount || options.month.visibleWeeksCount > 4)) {
          html.push(this.currentCalendarDate('YYYY.MM'));
        } else {
          html.push(moment(cal.getDateRangeStart().getTime()).format('YYYY.MM.DD'));
          html.push(' ~ ');
          html.push(moment(cal.getDateRangeEnd().getTime()).format(' MM.DD'));
        }
        this.rangeText = html.join('');
        this.rangeTime = [moment(cal.getDateRangeStart().getTime()).format('YYYY-MM-DD'), moment(cal.getDateRangeEnd().getTime()).format('YYYY-MM-DD')];
        this.getTask(this.rangeTime)
      })
    },

    currentCalendarDate(format) {
      const cal = this.$refs.cal.getInstance();
      let currentDate = moment([cal.getDate().getFullYear(), cal.getDate().getMonth(), cal.getDate().getDate()]);
      return currentDate.format(format);
    },

    onBeforeCreateSchedule({start, end, isAllDay, guide}) {
      if (isAllDay || this.calendarView == 'month') {
        start = $A.date2string(start.toDate(), "Y-m-d 00:00:00")
        end = $A.date2string(end.toDate(), "Y-m-d 23:59:59")
      } else {
        start = $A.date2string(start.toDate(), "Y-m-d H:i:s")
        end = $A.date2string(end.toDate(), "Y-m-d H:i:s")
      }
      this.start_at = start
      this.end_at = end
      this.task_id = null
      this.taskAddRef.ready = false
      this.$nextTick(()=>{
        this.taskAddRef.ready = true
      })
    },

    onBeforeClickSchedule(event) {
      const {type, schedule} = event;
      console.log("点击事件", type)
      let data = this.cacheTasks.find(({id}) => id === schedule.id);
      console.log(data)


      if (!data) {
        return;
      }
      switch (type) {
        case "check":
          if(data.isEdit==0){
            this.$message({
              message:'无修改权限',
              type: 'warning',
              duration: 1000,
              showClose: true
            })
            return;
          }
          this.calendarMenuStyles = {
            left: `${this.getElementLeft(event.target)}px`,
            top: `${this.getElementTop(event.target) - 8}px`
          }
          this.calendarTask = data;
          this.$nextTick(this.$refs.calendarTaskMenu.show);
          break;

        case "edit":
          let task_id = data;
          if ($A.isJson(data)) {
            if (data.parent_id > 0) {
              this.task_id = data.parent_id;
            } else {
              this.task_id = data.id;
            }
          }
          this.taskAddRef.ready = false
          this.$nextTick(()=>{
            this.taskAddRef.ready = true
          })
          break;

        case "delete":
          if(data.isEdit==0){
            this.$message({
              message:'无删除权限',
              type: 'warning',
              duration: 1000,
              showClose: true
            })
            return;
          }
          MessageBox.confirm('你确定要删除任务【' + data.name + '】吗？','提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
           if(this.isLocal){
             axios({
               method: 'post',
               url: this.web_manager.del_api,
               data: {
                 "delList": [data.id]
               }
             }).then((res) => {
               if (res.data.code !== 0) {
                 this.$message({
                   message: res.data.desc,
                   type: 'error',
                   duration: 1000,
                   showClose: true
                 })
               }else{
                 this.$message({
                   message: '删除成功',
                   type: 'success',
                   duration: 1000,
                   showClose: true
                 })
                 this.setRenderRange()
               }
             })
           }else{
             this.$magicaltool.request.axios({
               $vue:this,method:"post",contentType:"application/json",
               url:this.web_manager.del_api,
               responseType:"",
               data:{
                 "delList": [data.id]
               }
             }).then((res)=> {
               if (res.code !== 0) {
                 this.$message({
                   message: res.desc,
                   type: 'error',
                   duration: 1000,
                   showClose: true
                 })
               }else{
                 this.$message({
                   message: "删除成功",
                   type: 'success',
                   duration: 1000,
                   showClose: true
                 })
                 this.setRenderRange()
               }
             })
           }


          })
          break;
      }
    },

    onBeforeUpdateSchedule(res) {
      const {changes, schedule} = res;
      let data = this.cacheTasks.find(({id}) => id === schedule.id);
      if (!data || data.isEdit==0) {
        this.$message({
          message:'无操作权限',
          type: 'warning',
          duration: 1000,
          showClose: true
        })
        return;
      }
      if (changes.start || changes.end) {
        const cal = this.$refs.cal.getInstance();
        cal.updateSchedule(schedule.id, schedule.calendarId, changes);
        let start_sjc =changes.start? new Date(changes.start._date).getTime():new Date(schedule.start._date).getTime()
        let end_sjc =changes.end? new Date(changes.end._date).getTime():new Date(schedule.end._date).getTime()
        start_sjc = new Date(start_sjc).toLocaleString('chinese', { hour12: false }).replaceAll('/', '-')
        end_sjc = new Date(end_sjc).toLocaleString('chinese', { hour12: false }).replaceAll('/', '-')

        let info = {
          id:data.id,
          start_at:start_sjc,
          end_at:end_sjc,
        }
        this.updCaledar(info)
      }
    },
    updCaledar(data){
      if(this.isLocal){
        axios({
          method: 'post',
          url: this.web_manager.upd_api,
          data: data
        }).then((res) => {
          if (res.data.code !== 0) {
            this.$message({
              message: res.data.desc,
              type: 'error',
              duration: 1000,
              showClose: true
            })
          }else{
            this.$message({
              message: "修改成功",
              type: 'success',
              showClose: true,
              duration: 1000
            })
            this.setRenderRange()
          }
        })
      }else{
        this.$magicaltool.request.axios({
          $vue:this,method:"post",contentType:"application/json",
          url: this.web_manager.upd_api,
          responseType:"",
          data:data
        }).then((res)=> {
          if (res.code !== 0) {
            this.$message({
              message: res.desc,
              type: 'error',
              duration: 1000,
              showClose: true
            })
          }else{
            this.$message({
              message: "修改成功",
              type: 'success',
              showClose: true,
              duration: 1000
            })
            this.setRenderRange()
          }
        })
      }


    },

    getElementLeft(element) {
      let actualLeft = element.offsetLeft;
      let current = element.offsetParent;
      while (current !== null) {
        if (current == this.$el) break;
        actualLeft += (current.offsetLeft + current.clientLeft);
        current = current.offsetParent;
      }
      return actualLeft;
    },

    getElementTop(element) {
      let actualTop = element.offsetTop;
      let current = element.offsetParent;
      while (current !== null) {
        if (current == this.$el) break;
        actualTop += (current.offsetTop + current.clientTop);
        current = current.offsetParent;
      }
      return actualTop;
    },

    //下面是web端调用的方法
    closeDialog(param){
      if(param.msg && param.result===true){
        this.$message({
          message: param.msg,
          type: 'success',
          showClose: true,
          duration: 1000
        })
      }else if(param.msg && param.result===false){
        this.$message({
          message: param.msg,
          type: 'error',
          showClose: true,
          duration: 1000
        })
      }
      this.taskAddRef.ready = false
      this.setRenderRange()
    }
  }
}
</script>
<style lang="scss">
@import "statics/public/css/iview.css";
@import "statics/sass/pages/_.scss";
.tui-full-calendar-vlayout-area{
  height: 100% !important;
}
.tui-view-52{
  height: 100% !important;
}
</style>
